package myutil;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

@SuppressWarnings("unused")
public class LuceneIndexer {
	public String indexpath = new String("");
	public MyStemmer ms = new MyStemmer();
	public ArrayList<MyDocModel> docs = new ArrayList<MyDocModel>();

	public LuceneIndexer() {
		// TODO Auto-generated constructor stub
	}

	public LuceneIndexer(String indexpath) {
		// TODO Auto-generated constructor stub
		this.indexpath = indexpath;
	}

	public LuceneIndexer(String indexpath, MyStemmer ms) {// can use a class
															// extends mystemmer
		// TODO Auto-generated constructor stub
		this.indexpath = indexpath;
		this.ms = ms;
	}

	/**
	 * @param args
	 */
	public int ProcessIndex() {
		Date start = new Date();
		try {
			IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40,
					ms.GetAnalyzer());
			iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
			Directory dir = FSDirectory.open(new File(this.indexpath));
			IndexWriter writer = new IndexWriter(dir, iwc);
			try {

				for (MyDocModel md : docs) {
					Document lc_d = new Document();
					lc_d.add(new IntField("id", md.docid, Field.Store.YES));
					lc_d.add(new TextField("title", md.title, Field.Store.YES));
					lc_d.add(new TextField("content", md.content,
							Field.Store.NO));
					//add other field
					for(String k :md.otherfeildnew.keySet())
						lc_d.add(new TextField(k,md.otherfeildnew.get(k),Field.Store.YES));
					writer.addDocument(lc_d);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				
				writer.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Date end = new Date();
		return (int)(end.getTime()-start.getTime());
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
